<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
    <style>
      img {
        border: 1px solid red;
        height: 200px;
        width: 200px;
        position: absolute;
      }
    </style>
  </head>
  <body>
    <img src="static/pig.jpg" id="pic"/>
  </body>
  
  <script>
    var dx = 25;
    var dy = 0;
    
    var x = 0;
    var y = 0;
    
    var intervalID = setInterval('movePic()', 100);
    
    //用到定时器  关闭此窗口后该定时器也关闭
    
    function movePic() {
      if ((x + 200) >= document.documentElement.clientWidth) {
        dx = 0;
        dy = 25;
        x = document.documentElement.clientWidth - 200;
      }
      if ((y + 200) >= document.documentElement.clientHeight) {//获取显示区的高度
        dx = -25;
        dy = 0;
        y = document.documentElement.clientHeight - 200;
      }
      if (x < 0) {//<=不可取
        dx = 0;
        dy = -25;
        x = 0;
      }
      if (y < 0) {
        dx = 25;
        dy = 0;
        y = 0;
      }
      x += dx;
      y += dy;
      
      document.getElementById('pic').style.left = x + 'px';
      document.getElementById('pic').style.top = y + 'px';
      
    }
  </script>
</html>
